package _3LoginExample;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginCheckServlet
 */
@WebServlet("/loginchk")
public class LoginCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginCheckServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		// HttpServletRequest request 
				// Tomcat自动创建的对象，会把用户的请求信息放入
				
//				HttpServletResponse response
				// Tomcat自动创建的对象, 通过它给用户发信息
				
				// 1. 获取用户提交的参数
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				
				
				// 2. 判断
				// 3. 显示结果
				if(("zhangsan".equals(username)&&"123456".equals(password))||
					("lisi".equals(username)&&"123456".equals(password))	
						)
				{
//					resp.getWriter().print("Login OK");
					
					// 保存登录信息
					HttpSession session = request.getSession();
					session.setAttribute("username", username);
					// 注意: 如果是项目中，则将查询到的User对象放入Session
					
					// 跳转首页
					response.sendRedirect("index");
					
				}
				else
				{
//					response.getWriter().print("Login fail");
					
					// 跳转到登录也
					response.sendRedirect("login.html");
				}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
